﻿using DataModels.Dto;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SEGIService;

public class ControllerExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        // 记录异常日志
        Console.WriteLine($"Global Exception: {context.Exception.Message}");
        Console.WriteLine(context.Exception.StackTrace);

        // 创建统一的错误响应
        var responseModel = new ResponseModel
        {
            Code = 500,
            Message = "服务器内部错误，请稍后重试",
            Data = null
        };

        //自定义错误类型
        if(context.Exception is SEGIException SEGIEx)
        {
            responseModel.Code = SEGIEx.ErrorCode;
            responseModel.Message = SEGIEx.Message;
            responseModel.Data = SEGIEx.ErrorData;
        }
        // 已知异常类型
        else if (context.Exception is ArgumentNullException)
        {
            responseModel.Code = 400;
            responseModel.Message = "参数不能为空";
        }
        else if (context.Exception is UnauthorizedAccessException)
        {
            responseModel.Code = 401;
            responseModel.Message = "未授权访问";
        }

        // 设置HTTP状态码和响应内容
        context.Result = new ObjectResult(responseModel)
        {
            StatusCode = responseModel.Code
        };

        // 标记异常已处理
        context.ExceptionHandled = true;
    }
}